import { globalConfig } from './../../base/config/globalConfig';
import { WxliteTokenStorage } from './wx.token';
import {
    IMiniProgramUserInfo,
    OpenidResponse,
    wxConfig,
    wxLiteConfig,
} from './wx.definition';
import { Injectable } from '@nestjs/common';
import { HttpService } from "./../../base/services/http.service";
import * as crypto from 'crypto';
import * as path from 'path';
@Injectable()
export class WxliteService {
    constructor(
        private httpService: HttpService,
        private wxliteTokenStorage: WxliteTokenStorage,
    ) {}
    /**
     * 解析出小程序用户的数据来
     */
    async decryptUserData(
        code: string,
        encryptedData: string,
        iv: string,
    ): Promise<IMiniProgramUserInfo> {
        let json: OpenidResponse = await this.httpService.get(
            'https://api.weixin.qq.com/sns/jscode2session',
            {
                appid: wxLiteConfig.app_id,
                secret: wxLiteConfig.app_secret,
                js_code: code,
                grant_type: 'authorization_code',
            },
        );
        // 如果发生了错误 没有拿到数据
        if (json.errcode && json.errmsg) {
            throw json;
        }
        return this.decrypt(json.session_key, encryptedData, iv);
    }

    private decrypt(
        $sessionKey: string,
        $encryptedData: string,
        $iv: string,
    ): IMiniProgramUserInfo {
        const sessionKey = new Buffer($sessionKey, 'base64');
        const encryptedData = new Buffer($encryptedData, 'base64');
        const iv = new Buffer($iv, 'base64');

        // 解密
        const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
        decipher.setAutoPadding(true);
        let decoded = decipher.update(encryptedData, 'binary' as any, 'utf8');
        decoded += decipher.final('utf8');
        return JSON.parse(decoded);
    }

    /**
     * 获取小程序码
     */
    async getQrcode(scene: string = 'from=server'): Promise<Buffer> {
        let ACCESS_TOKEN = await this.wxliteTokenStorage.genToken();
        return await this.httpService.post(
            `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${ACCESS_TOKEN}`,
            {
                data: { scene },
                headers: {
                    'Content-Type': 'application/json', // POST 参数需要转成 JSON 字符串，不支持 form 表单提交。
                },
                responseType: 'arraybuffer', // 重点
            },
        );
    }
}
